<?php
/**
 * 文章表单模型
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/1/18
 * Time: 10:35
 */

namespace frontend\models;
use common\models\PostModel;
use common\models\RelationPostTagsModel;
use Yii;
use yii\base\Model;
use yii\db\Query;
use yii\web\NotFoundHttpException;

class PostForm extends Model
{

    //映射到数据表的字段
    public $id;
    public $title;
    public $content;
    public $label_img;
    public $tags;
    public $cat_id;

    public $_lastError = "";

    /**
     * 定义场景(?为什么要有场景)
     * SCENARIOS_CREATE 创建
     * SCENARIOS_UPDATE 更新
     */
    const SCENARIOS_CREATE = 'create';
    const SCENARIOS_UPDATE = 'update';

    /**
     * 定义事件
     * EVENT_AFTER_CREATE
     * EVENT_AFTER_UPDATE
     */
    const EVENT_AFTER_CREATE = 'eventAfterCreate';
    const EVENT_AFTER_UPDATE = 'eventAfterUpdate';

    public function scenarios()
    {
        $scenarios = [
            self::SCENARIOS_CREATE => ['title','content','label_img','cat_id','tags',],
            self::SCENARIOS_UPDATE => ['title','content','label_img','cat_id','tags'],
        ];
        return array_merge(parent::scenarios(), $scenarios);
    }

    //自定义的ruler规则
    public function rules()
    {
        return [
            [['id','title','content','cat_id'],'required'],
            [['id','cat_id'],'integer'],
            ['title','string','min'=>4,'max'=>50],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id'=>'编码',
            'title'=>'标题',
            'content'=>'内容',
            'label_img'=>'标签图',
            'tags'=>'标签',
            'cat_id'=>'分类',
        ];
    }

    public static function getList($cond, $curPage = 1, $pageSize = 5, $orderBy = ['id'=>SORT_DESC] )
    {
        $model = new PostModel();
        //查询语句
//        var_dump($cond);exit;
        $select = ['id','title','summary','label_img','cat_id','user_id','user_name','is_valid','created_at','updated_at'];
        $query = $model->find()
            ->select($select)
            ->where($cond)
            ->with('relate.tag','extend')
            ->orderBy($orderBy);

        //获取分页数据
//        $res = $model->getPage($query, $curPage, $pageSize);
        $res = $model->getPages($query, $curPage, $pageSize);//var_dump($res);exit;
        //个格式化数据
        $res['data'] = self::_formatList($res['data']);
        return $res;
    }

    /**
     * 数据格式化
     * @param $data
     * @return mixed
     */
    public static  function _formatList($data)
    {
        foreach($data as &$list) {
            $list['tags'] = [];
            if(isset($list['relate']) && !empty($list['relate'])) {
                foreach($list['relate'] as $lt) {
                    $list['tags'][] = $lt['tag']['tag_name'];
                }
            }
            unset($list['relate']);
        }
        return $data;
    }

    /**
     * 文章创建
     * @return bool
     */
    public function create()
    {
        //事务处理
        $transaction = Yii::$app->db->beginTransaction();
        try{

            $model = new PostModel();
            $model->setAttributes($this->attributes);
            $model->summary = $this->_getSummary(); //文章简介的方法
            $model->user_id = Yii::$app->user->identity->id;
            $model->user_name = Yii::$app->user->identity->username;
//            $model->label_img = Yii::$app->user->identity->label_img;
            $model->created_at = time();
            $model->updated_at = time();
            if(!$model->save())
                throw new \Exception('文章保存失败！'); //可以用语言包

            $this->id = $model->id;

            //调用事件
            $data = array_merge($this->getAttributes(), $model->getAttributes());
            $this->_eventAfterCreate($data);

            $transaction->commit();
            return true;
        }catch (\Exception $e) {
            $transaction->rollBack();
            $this->_lastError = $e->getMessage();
            return false;
        }

    }

    public function getViewById($id)
    {
        $res = PostModel::find()->with('relate.tag','extend')->where(['id'=>$id])->asArray()->one();
        if(!$res) {
            throw new NotFoundHttpException('文章不存在！');
        }

        //处理标签格式
        $res['tags'] = [];
        if(isset($res['relate']) && !empty($res['relate'])) {
            foreach($res['relate'] as $list) {
                $res['tags'][] = $list['tag']['tag_name'];
            }
        }
        unset($res['relate']);
//        print_r($res);exit;
        return $res;
    }

    /**
     * 截取文章摘要
     * @param int $s
     * @param int $end
     * @param string $char
     * @return null|string
     */
    private function _getSummary($s = 0, $end = 90, $char = 'utf-8')
    {
        if(empty($this->content))
            return null;
        return (mb_substr(str_replace('&nbsp;','',strip_tags($this->content)),$s, $end,$char));
    }

    /**
     * 文章创建之后的事件
     * @param $data
     */
    public function _eventAfterCreate($data)
    {
        //添加事件
        $this->on(self::EVENT_AFTER_CREATE, [$this, '_eventAddTag'], $data);
        //触发事件
        $this->trigger(self::EVENT_AFTER_CREATE);
    }


    /**
     * 添加标签
     */
    public function _eventAddTag($event)
    {
        //保存标签
        $tag = new TagForm();
        $tag->tags = $event->data['tags'];
        $tagIds = $tag->saveTags();

        //删除原先的关联关系
        RelationPostTagsModel::deleteAll(['post_id' => $event->data['id']]);

        //批量保存文章标签的关联关系
        if(!empty($tagIds)) {
            foreach($tagIds as $k=>$id) {
                $row[$k]['post_id'] = $this->id;
                $row[$k]['tag_id'] = $id;
            }
            //批量插入
            $res = (new Query())->createCommand()
                ->batchInsert(RelationPostTagsModel::tableName(),['post_id','tag_id'], $row)
                ->execute();
            //返回结果45士
            if(!$res)
                throw new \Exception('关联关系保存失败！');
        }
    }
}